package com.szholly.pro.watergas_server.ps.schedule;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.szholly.data.general.RowBase;
import com.szholly.plug.form.excel.utils.StringUtil;
import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.ps.monitor.MonitorDataType;
import com.szholly.pro.watergas_server.ps.monitor.MonitorWaterType;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import lrq.common.MyLog;
import lrq.common.PropertiesUnit;

public class DataAlarmIPS implements Job {
	
	static Logger log;
	MonitorWaterType monitorWaterType=new MonitorWaterType();
	public static String platCode = "4";  //平台编码 废气：4
	
	/**
	 * 判别工业污染源（废水废气）数据超标
	 * wencheng
	 * 2017年2月22日
	 */
	private void FindIPSDataAlarm(Date date){
		try{
	        //循环站点    工业废水、工业废气所有站点  
			log.info("开始生成工业污染源超标信息");
			HashMap<String, String> hourAlarmPointCodes = PropertiesUnit.getMap("hourAlarmPointCodes");
	        String sql = "select t1.id,t1.device_num,t2.STATION_CATEGORY from BC_COLLECTION_INFO t1 "
	        		+ " left join BC_SITE_INFO t2 on t1.SITE_ID=t2.exp_no"
	        		+ " where t2.STATION_CATEGORY = '"+ platCode +"'"
	        		+ " order by t2.station_category";
			List<RowBase> rows = DataUtil.getSelectRows(sql, null);
			if(rows.size()>0){
				for(int i=0;i<rows.size();i++){
					RowBase row = rows.get(i);
					String strMN = row.getSafeString("device_num");
					//分表
					String WATER_TYPE = row.getSafeString("STATION_CATEGORY");
					if(hourAlarmPointCodes.containsKey(strMN))
					{   
						FindIPSHourDataAlarm(strMN,date,WATER_TYPE);
					}else{
						FindIPSMinuteDataAlarm(strMN,date,WATER_TYPE);
					}
				}
			}	
		}
		catch (Exception e) {
			log.error("生成工业污染源超标信息",e);
		}
	}
	
	
	/**
	 * 判别工业污染源（废水废气）数据超标(小时数据)
	 * wencheng
	 * 2017年2月22日
	 */
	private void FindIPSHourDataAlarm(String strMN,Date date,String WATER_TYPE){
		try{
			//每小时第20分钟进行小时数据报警记录生成工作
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int minute = cal.get(Calendar.MINUTE);
			if(minute != 20){
				return;
			}
			
			log.info("开始生成（工业污染源）小时数据超标信息");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH");
			String strDateTime = sdf.format(date);
			strDateTime += ":00:00"; 
			date = sdf.parse(strDateTime);  
			//分表
			String tableName="BD_MO_HOUR";
		    if(StringUtil.IsNotNullOrEmpty(WATER_TYPE)&&!WATER_TYPE.equals("3")){
		    	MonitorDataType md=monitorWaterType.getWaterType(WATER_TYPE, "hour");
				tableName=md.getTableName();
		    }
		    else{
		    	tableName="BD_MO_HOUR";
		    }	
			//获取小时数据，取均值
			String sql = "select t.parmname,t.avg,t.zs_avg from "+tableName+" t where t.mn = '"+strMN+"'"
							+ " and t.datatime = to_date('"+strDateTime+"', 'yyyy-mm-dd hh24:mi:ss')";
			List<RowBase> parmRows = DataUtil.getSelectRows(sql, null); 
			if(parmRows.size()>0){
				for(int j=0;j<parmRows.size();j++){
					RowBase parmRow = parmRows.get(j);
					String strParm = parmRow.getSafeString("parmname");
					Double dValue = parmRow.getDouble("avg");
					Double dValueZS = parmRow.getDouble("zs_avg");
					//比较各个阈值上下限，生成报警数据
					DataAlarm.createMulThreDataAlarm(strMN,strParm,dValue,dValueZS,date,"小时数据");
				}
			}
		}
		catch (Exception e) {
			log.error("生成（工业污染源）小时数据超标信息出错",e);
		}
	}
	
	/**
	 * 判别工业污染源（废水废气）数据超标(分钟数据)
	 * wencheng
	 * 2017年2月22日
	 */
	private void FindIPSMinuteDataAlarm(String strMN,Date date,String WATER_TYPE){
		try{
			//对10求余的值为2和6分钟进行数据报警记录生成工作
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			int minute = cal.get(Calendar.MINUTE);
			if((minute%10)!=2 && (minute%10)!=6){
				return;
			}
			log.info("开始生成（工业污染源）分钟数据超标信息");
			if((minute%10)==2)
			{
				cal.add(Calendar.MINUTE,-7);
			}else
			{
				cal.add(Calendar.MINUTE,-6);
			}
			
			date = cal.getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm");
			String strDateTime = sdf.format(date);
			strDateTime += ":00"; 
			date = sdf.parse(strDateTime); 
			//分表
			String tableName="BD_MO_MIN";
		    if(StringUtil.IsNotNullOrEmpty(WATER_TYPE)&&!WATER_TYPE.equals("3")){
		    	MonitorDataType md=monitorWaterType.getWaterType(WATER_TYPE, "minute");
				tableName=md.getTableName();
		    }
		    else{
		    	tableName="BD_MO_MIN";
		    }	
			//获取分钟数据，取均值
			String sql = "select t.parmname,t.avg,t.zs_avg from "+tableName+" t where t.mn = '"+strMN+"'"
							+ " and t.datatime = to_date('"+strDateTime+"', 'yyyy-mm-dd hh24:mi:ss')";
			List<RowBase> parmRows = DataUtil.getSelectRows(sql, null); 
			if(parmRows.size()>0){
				for(int j=0;j<parmRows.size();j++){
					RowBase parmRow = parmRows.get(j);
					String strParm = parmRow.getSafeString("parmname");
					Double dValue = parmRow.getDouble("avg");
					Double dValueZS = parmRow.getDouble("zs_avg");
					//比较各个阈值上下限，生成报警数据
					DataAlarm.createMulThreDataAlarm(strMN,strParm,dValue,dValueZS,date,"5分钟数据");
				}
			}
		}
		catch (Exception e) {
			log.error("生成（工业污染源）分钟数据超标信息出错",e);
		}
	}
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		if(log == null){
			log = MyLog.getLogger("DataAlarmIPS");
		}
		 
		try {
			Date date = arg0.getFireTime();
			FindIPSDataAlarm(date);
		} catch (Exception e) {
			log.error("生成工业污染源超标报警信息出错",e);
		}
	}
	
	public void execute() throws JobExecutionException{
		execute(null);
	}

}
